package com.hxzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.MarketingThreadLocalUtil;
import com.hxzy.controller.mobile.addressbook.req.AddressBookAddReq;
import com.hxzy.controller.mobile.mapstruct.AddressBookConvert;
import com.hxzy.entity.AddressBook;
import com.hxzy.service.AddressBookService;
import com.hxzy.mapper.AddressBookMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
* @author 11452
* @description 针对表【address_book(地址管理)】的数据库操作Service实现
* @createDate 2023-08-28 11:54:55
*/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>
    implements AddressBookService{

    @Override
    public boolean add(AddressBookAddReq req) {
        //谁买的
        Integer userId = MarketingThreadLocalUtil.mobileThreadLocal.get().getId();

        //查询该用户是否有默认的收货地址
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId);
        queryWrapper.eq(AddressBook::getIsDeleted,"0");
        queryWrapper.eq(AddressBook::getIsDefault,"0");
        long count = super.count(queryWrapper);

        //转换自己的对象
        AddressBook entity = AddressBookConvert.INSTANCE.convert(req);
        entity.setUserId(Long.valueOf(userId));
        entity.setIsDeleted("0");

        //是否是默认值
        entity.setIsDefault( count==0?"0": "1");

        return super.save(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateDefaultAddress(Long id) {
        //1、先查询数据在不在
        AddressBook db = this.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //2、如果当前收地址是默认，就不要做操作
        if(db.getIsDefault().equals("0")){
            return true;
        }

        Integer userId = MarketingThreadLocalUtil.mobileThreadLocal.get().getId();

        //3、先更新的用户默认收货地址取消
        long count=this.baseMapper.cancelDefaultAddress(userId);

        //4、更新当前数据为默认收货地址
        db.setIsDefault("0");
        this.updateById(db);

        return true;
    }
}




